package cn.pku.ss.fa.ui.component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.naming.InitialContext;
import org.zkoss.zk.ui.Path;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zul.Captcha;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import cn.pku.ss.fa.bean.CityBean;
import cn.pku.ss.fa.bean.EducationExperience;
import cn.pku.ss.fa.bean.PersonalBean;
import cn.pku.ss.fa.bean.ProvinceBean;
import cn.pku.ss.fa.bean.WorkExperience;
import cn.pku.ss.fa.sessionbean.CityDAORemote;
import cn.pku.ss.fa.sessionbean.CityManagerLocal;
import cn.pku.ss.fa.sessionbean.UserManagerLocal;
import cn.pku.ss.fa.ui.Common;
import cn.pku.ss.fa.ui.URLStrategy;

public class RegisterWindowComponent extends Window {

	private List<ProvinceBean> provinces;
	private List<CityBean> currentCities;

	public RegisterWindowComponent() {
		try {
			InitialContext ctx = new InitialContext();
			CityManagerLocal cityManager = (CityManagerLocal) ctx
					.lookup("FriendsAnywhere/CityManager/local");
			CityDAORemote cityDao = (CityDAORemote)ctx
			.lookup("FriendsAnywhere/CityDAO/remote");
			cityDao.insertCities();
			
			provinces = cityManager.findAllProvinces();
			for (ProvinceBean province : provinces) {
				currentCities = province.getCityNames();
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onProvinceSelect(int provinceId) {
		Listbox selectCities = (Listbox) getFellow("selectCities");
		selectCities.getChildren().clear();

		for (ProvinceBean province : provinces) {
			if (province.getId() == provinceId) {
				currentCities = province.getCityNames();
				break;
			}
		}

		for (CityBean city : currentCities) {
			selectCities.appendChild(getNewListitem(city));
		}
		selectCities.setSelectedIndex(0);
	}

	public void onRegisterNow(){
		Captcha captcha = (Captcha)getFellow("captcha");
		Textbox verify = (Textbox)getFellow("verify");
		if(!captcha.getValue().equalsIgnoreCase(verify.getText())){
			throw new WrongValueException(verify, "Invalidate code!");
		}
		
		// basic
		Textbox userName = (Textbox)getFellow("userName");
		Textbox password = (Textbox)getFellow("password");
		Textbox realName = (Textbox)getFellow("realName");
		Datebox birthday = (Datebox)getFellow("birthday");
		Listbox selectCities = (Listbox)getFellow("selectCities");
		
		// eduction
		Datebox startTime = (Datebox)getFellow("startTime");
		Datebox endTime = (Datebox)getFellow("endTime");
		Textbox school = (Textbox)getFellow("school");
		Textbox experience = (Textbox)getFellow("experience");
		
		// work
		Textbox company = (Textbox)getFellow("company");
		Textbox position = (Textbox)getFellow("position");
		Textbox description = (Textbox)getFellow("description");
		
		// contact
		Textbox qq = (Textbox)getFellow("qq");
		Textbox msn = (Textbox)getFellow("msn");
		Textbox phone = (Textbox)getFellow("phone");
		Textbox site = (Textbox)getFellow("site");
		
		PersonalBean user = new PersonalBean();
		user.setUserName(userName.getText());
		user.setPassword(password.getText());
		user.setRealName(realName.getText());
		user.setBirthDay(birthday.getText());
		CityBean city = new CityBean();
		city.setId((Integer)selectCities.getSelectedItem().getValue());
		user.setCity(city);
		
		List<EducationExperience> educationExperiences = new ArrayList<EducationExperience>();
		if(!isEmpty(startTime.getText())&&!isEmpty(endTime.getText())&&!isEmpty(school.getText())
				&&!isEmpty(experience.getText())){
			EducationExperience educationExperience1 = new EducationExperience();
			educationExperience1.setStartDate(startTime.getText());
			educationExperience1.setEndDate(endTime.getText());
			educationExperience1.setSchool(school.getText());
			educationExperience1.setExperience(experience.getText());
			educationExperiences.add(educationExperience1);
		}
		user.setEducationExperiences(educationExperiences);
		
		List<WorkExperience> workExperiences = new ArrayList<WorkExperience>();
		if(!isEmpty(company.getText())&&!isEmpty(position.getText())&&!isEmpty(description.getText())){
			WorkExperience workExperience = new WorkExperience();
			workExperience.setCompany(company.getText());
			workExperience.setPosition(position.getText());
			workExperience.setDescription(description.getText());
			workExperiences.add(workExperience);
		}
		user.setWorkExperiences(workExperiences);
		
		user.setQq(qq.getText());
		user.setMsn(msn.getText());
		user.setPhoneNumber(phone.getText());
		user.setSite(site.getText());
		
		user.setProfile("/image/defaultHeadPhoto.gif");
		user.setStatus("");
		
		boolean success = true;
		try {
			InitialContext ctx = new InitialContext();
			UserManagerLocal userDao = (UserManagerLocal)ctx.lookup("FriendsAnywhere/UserManager/local");
			success = userDao.registerUser(user);
			if(success){
				Textbox nameTextBox = (Textbox)Path.getComponent("//loginPage/nameTextBox");
				Textbox passwordTextBox = (Textbox)Path.getComponent("//loginPage/passwordTextBox");
				passwordTextBox.setText(user.getPassword());
				nameTextBox.setText(user.getUserName());
				
				int userId = userDao.login( user.getUserName(), user.getPassword() ).getId();  //get user Id
				this.doRegisterSuccess(userId);
				
				this.onClose();
				return;
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		if(!success){
			throw new WrongValueException(userName, "This user name has been used!");
		}
	}
	
	private boolean isEmpty(String content){
		return content==null||content.equalsIgnoreCase("");
	}

	private Listitem getNewListitem(CityBean city) {
		Listitem tmp = new Listitem();
		tmp.setLabel(city.getCityName());
		tmp.setValue(city.getId());
		return tmp;
	}

	public List<ProvinceBean> getProvinces() {
		return provinces;
	}

	public List<CityBean> getCurrentCities() {
		return currentCities;
	}
	
	//////////////////////////////////////////////////////////////////////////////

	private void doRegisterSuccess(int userId) {
		//create user directories:
		//album
		String albumRoot = Common.getWebRootRealPath() + URLStrategy.getAlbumRootURL(userId);
		if( !new File(albumRoot).mkdirs() ) {
			System.out.println( "Create directories failed: "+albumRoot );
		}
		
	}
	
}
